import unittest
import personality

class fakeResult(object):
    def __init__(self, failures=0, errors=0, passed=0):
        self.failures = [False] * failures
        self.errors = [False] * errors
        self.testsRun = passed + failures + errors
    def __str__(self):
        return "FakeResult: %d failed, %d errors, %d run" % (
            len(self.failures),
            len(self.errors),
            self.testsRun
            )

class PersonalityTest(unittest.TestCase):
    class fakeTimer(object):
        def __init__(self):
            self.nextTime= 0;
        def setTime(self, time):
            self.nextTime = time;
        def __call__(self):
            return self.nextTime

    def setUp(self):
        self.timer = self.fakeTimer()
        self.commentInterval = 500
        self.personality = personality.Personality(
            self.commentInterval, 
            self.timer
            )

    def incrementTime(self, ms):
        self.timer.setTime(self.timer() + ms)

    def passATestRun(self):
        result = fakeResult(failures=0,errors=0,passed=1)
        self.personality.update(result)

    def testPersonalityKnowsWhenItIsGreen(self):
        self.passATestRun()
        self.failUnlessEqual(True, self.personality.isGreen())
        self.failUnlessEqual(False, self.personality.hasErrors())
        self.failUnlessEqual(False, self.personality.hasFailures())

    def testPersonalityKnowsWhenItHasFailuresItIsNotGreen(self):
        personality = self.personality
        result = fakeResult(failures=1,errors=0,passed=0)
        personality.update(result)
        self.failUnlessEqual(False, personality.isGreen())
        self.failUnlessEqual(True, personality.hasFailures())
        self.failUnlessEqual(False, self.personality.hasErrors())

    def testPersonalityKnowsWhenItHasErrorsItIsNotGreen(self):
        personality = self.personality
        result = fakeResult(failures=0,errors=1,passed=0)
        personality.update(result)
        self.failUnlessEqual(False, personality.isGreen())
        self.failUnlessEqual(False, personality.hasFailures())
        self.failUnlessEqual(True, self.personality.hasErrors())

    def testLastGreenIsTracked(self):
        personality = self.personality
        self.passATestRun()

        self.incrementTime(2000)
        self.failUnlessEqual(2000, personality.msSinceLastGreen())

        self.incrementTime(2000)
        self.failUnlessEqual(4000, personality.msSinceLastGreen())

    def testTracksLastUpdate(self):
        personality = self.personality
        self.passATestRun()
        self.incrementTime(1000)
        self.failUnlessEqual(1000, personality.msSinceLastUpdate())

        self.personality.update( fakeResult(errors=1) )
        self.incrementTime(1000)


if __name__ == "__main__":
    unittest.main()
